//
//  ServiceOutlet.swift
//  home
//
//  Created by Yun Zeng on 2019/9/15.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

// 插座
class ServiceOutlet {
    var service: Service
    
    var on: HMCharacteristic
    
    init?(service: Service) {
        if service.type != HMServiceType.outlet.rawValue {
            return nil
        }
        guard let on = service.findCharacteristic(type: .on) else {
            return nil
        }
        self.service = service
        self.on = on
    }
    
    enum State: Int {
        case on = 1
        case off = 0
    }
    
    var onState: State {
        get {
            if let value = on.value?.toValueInt() {
                if let state = State(rawValue: value) {
                    if state == .on && self.service.state == .online {
                        self.service.state = .highlight
                    }
                    return state
                }
            }
            return .off
        }
        set {}
    }
    
    func setPower(power: State) {
        self.service.state = .update
        self.onState = power
        let action = HomeAction(characteristic: self.on, targetValue: power.rawValue)
        if action != nil {
            _ = self.service.manager?.executeActions(actions: action!)
        }
    }
}

extension ServiceOutlet: ServiceCellDelegate {
    var icon: UIView {
        var imgSrc = ""
        if let icon = self.service.icon {
            if self.onState == .on && self.state != .offline {
                imgSrc = "service-" + icon + "-on"
            } else {
                imgSrc = "service-" + icon + "-off"
            }
        }
        let imageView = UIImageView(frame: ServiceCellView.iconSize)
        imageView.image = UIImage(named: imgSrc)
        return imageView
    }
    
    var room: String {
        if let name = self.service.room?.name {
            return name
        }
        return "默认房间"
    }
    
    var name: String {
        if self.service.name != "" {
            return self.service.name
        }
        return "请命名"
    }
    
    var state: Service.State {
        return self.service.state
    }
    
    var desc: String {
        if self.service.state == .offline {
            return "离线"
        }
        if self.onState == .on {
            return "开"
        }
        return "关闭"
    }
    
    func toggle() -> HomeAction? {
        var target = State.on
        if self.onState == .on {
            target = .off
        }
        self.service.state = .update
        self.onState = target
        let action = HomeAction(characteristic: self.on, targetValue: target.rawValue)
        return action
    }
}





